import { AuthApi, type LoginRO, type TokenVO } from '@/api';
import axios from 'axios';

class AuthService {
    private axiosInstance = axios.create();
    private authApi = new AuthApi(undefined, import.meta.env.VITE_API_URL, this.axiosInstance);

    isLoggedIn: boolean = false;

    private saveToken(token: TokenVO) {
        sessionStorage.setItem("access_token", token.access_token!);
        sessionStorage.setItem("refresh_token", token.refresh_token!);
        sessionStorage.setItem("user", JSON.stringify({})); // 存储用户信息
    }

    private clearToken() {
        sessionStorage.removeItem("access_token");
        sessionStorage.removeItem("refresh_token");
        sessionStorage.removeItem("user");
    }

    login(loginRo: LoginRO) {
        return this.authApi.login(loginRo).then((res) => {
            this.isLoggedIn = true; // 更新登录状态
            this.saveToken(res.data); // 存储 token
            return res;
        });
    }

    refreshToken() {
        let refreshToken = sessionStorage.getItem("refresh_token");
        return this.authApi.refresh(refreshToken!).then((res) => {
            this.saveToken(res.data);
            return res;
        });
    }

    logout() {
        this.clearToken();
        this.isLoggedIn = false; // 更新登录状态
    }

    // 检查用户是否已登录
    checkLoginStatus() {
        const user = sessionStorage.getItem("user");
        this.isLoggedIn = !!user; // 如果有用户信息，设置为 true
        return this.isLoggedIn;
    }
}

export const authService = new AuthService();